<?php

namespace app\admin\controller\user;

use app\admin\model\StundentTryLogs;
use app\admin\model\StundentVipLogs;
use app\admin\model\Grade;
use app\admin\model\GradeClass;
use app\admin\model\School;
use app\admin\model\Schoolclass;
use app\admin\model\VipConfig;
use app\common\controller\Backend;
use app\common\library\Auth;
use Exception;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->type = intval($this->request->param('type'));
        $this->assign('type',$this->type);
        $this->assignconfig('type',$this->type);

        $vipConfig_ =  (new VipConfig())->select();
        $vipConfig = array_column($vipConfig_,'type_desc','id');
        $this->assignconfig('vipConfig',$vipConfig);
        $this->assign('vipConfig',$vipConfig);
        $school_ =  (new School())->select();
        $school = array_column($school_,'name','id');
        $this->assignconfig('schoolConfig',$school);

        $grade_ =  (new Grade())->select();
        $grade = array_column($grade_,'gradeName','grade');
        $this->assignconfig('gradeConfig',$grade);

        $class_ =  (new GradeClass())->select();
        $class = array_column($class_,'grade_name','id');
        $this->assignconfig('classConfig',$class);

    }



    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('school,grade,grade_class,vipConfig')
                ->where($where)
                ->where('type',$this->type)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->getRelation('grade_class')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function import()
    {
        set_time_limit(0);
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);

        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $fieldArr = [
            "学校" => "school",
            "年级"  => "grade",
            "班级"  => "class",
            "学生姓名"  => "nickname",
            "系统编号"  => "system_no",
            "家长电话"  => "family_phone",
        ];

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if($val instanceof RichText){
                        //富文本转换字符串 这里非常的重要
                        $val = $val->__toString();
                    }
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if($val instanceof RichText){
                        //富文本转换字符串 这里非常的重要
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            $success = 0 ; $skip = 0;$fail = 0;$exist =0;
            $skip_list = [];$fail_list = [];$exist = [];
            foreach ($insert as $k => $v){
                $schoolModel = new School();
                $gradeModel = new Grade();
                $gradeClassModel = new GradeClass();
                $schoolClassModel = new Schoolclass();
                $school = $v['school'];
                $grade = $v['grade'];
                $class = $v['class'];
                $nickname = $v['nickname'];
                $system_no = $v['system_no'];
                $family_phone = $v['family_phone'];
                if (!$nickname){
                    continue;
                }
                //查询学校是否存在 不存在进行创建
                $schoolData  =$schoolModel->where("name",$school)->find();
                if (!$schoolData){
                    $skip++;
                    $skip_list[] = $nickname."-学校不存在".PHP_EOL;
//                     $schoolModel->save([
//                        "name" => $school,
//                        "city" => "",
//                        "create_time" => time(),
//                        "update_time" => time(),
//                    ]);
//                    $school_id = $schoolModel->getLastInsID();
                      continue;
                }else{
                    $school_id = $schoolData->id;
                }

                $gradeData  =$gradeModel->where("gradeName",$grade)->find();
                if (!$gradeData){
                    $skip++;
                    $skip_list[] = $nickname."-年级不存在".PHP_EOL;
                    continue;
                     $gradeModel->save([
                        "gradeName" => $grade,
                        "period" => 1000,
                    ]);
                    $grade_id = $gradeModel->getLastInsID();
                }else{
                    $grade_id = $gradeData->grade;
                }
                $gradeClassData  = $gradeClassModel->where("grade_id",$grade_id)->where("name",$class)->find();
                if (!$gradeClassData){
                    $skip_list++;
                    $skip_list[] = $nickname."-班级不存在".PHP_EOL;
                    continue;
                    $gradeClassModel->save([
                        "name" => $class,
                        "grade_id" => $grade_id,
                    ]);
                    $class_id = $gradeClassModel->getLastInsID();
                }else{
                    $class_id = $gradeClassData->id;
                }
                //系统编号不能唯一
                $system_noHas = $this->model->where("system_no",$system_no)->count();
                if ($system_noHas){
                    $skip++;
                    $skip_list[] = $nickname."-编号重复".PHP_EOL;
                    continue;
                }
                //判断手机号不能重复
                $system_noHas = $this->model->where("mobile",$family_phone)->count();
                if ($system_noHas){
                    $skip++;
                    $skip_list[] = $nickname."-手机号重复".PHP_EOL;
                    continue;
                }

                //查看学校班级表是否有数据
                //查看学校班级表是否有数据
                $has = $schoolClassModel->where("school_id",$school_id)->where("grade_id",$grade_id)->where("class_id",$class_id)->find();
                if (!$has && $school_id && $grade_id && $class_id){
                    //并且年级和班级需要匹配
                    $exist = (new GradeClass())->find($class_id);
                    if ($exist && $exist->grade_id == $grade_id){
                        $schoolClassModel->save([
                            "school_id" => $school_id,
                            "grade_id" => $grade_id,
                            "class_id" => $class_id,
                        ]);
                    }
                }

                $salt = Random::alnum();
                $re = (new \app\admin\model\User())->insert([
                    "group_id" => 0,
                    "type" => 2,
                    "salt" => Random::alnum(),
                    "password" =>  $this->getEncryptPassword('As123456', $salt),
                    "username" => $family_phone,
                    "nickname" => $nickname,
                    "mobile" => $family_phone,
                    "system_no" => $system_no,
                    "school_id" => $school_id,
                    "class_id" => $class_id,
                    "grade_id" => $grade_id,
                    "status" => "normal",
                    "createtime" => time(),
                    "updatetime" => time(),
                ]);
                if (!$re){
                    $skip_list[] = $nickname."-导入失败".PHP_EOL;
                }
                $re ? $success++ : $fail ++;
            }

        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $msg = "操作成功，{$success}条导入成功，{$fail}条导入失败，{$skip}条数据已经存在".PHP_EOL;
        $file_name = time().".csv";
        $msg.= "跳过明细：<a style='color: red' target='_blank' href='/tpl/{$file_name}'>点击查看</a> ";
        file_put_contents("./tpl/$file_name",$this->charsetToUTF8(implode("",$skip_list)));
        $this->success($msg,null,[],20);
    }


    protected function charsetToUTF8($mixed)
    {
        if (is_array($mixed)) {
            foreach ($mixed as $k => $v) {
                if (is_array($v)) {
                    $mixed[$k] = charsetToUTF8($v);
                } else {
                    $encode = mb_detect_encoding($v, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
                    if ($encode == 'EUC-CN') {
                        $mixed[$k] = iconv('GBK', 'UTF-8', $v);
                    }
                }
            }
        } else {
            $encode = mb_detect_encoding($mixed, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
            if ($encode == 'EUC-CN') {
                $mixed = iconv('GBK', 'UTF-8', $mixed);
            }
        }
        return $mixed;
    }


    public function selectpage()
    {
        $type = $this->request->get('type');

        $list = $this->model
            ->with('school,grade')
            ->where('type',$type)
            ->field("id","nickname")
            ->select();
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => count($list)]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }else{
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
//            if ($this->modelValidate) {
//                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
//                $this->model->validateFailException()->validate($validate);
//            }
            $params['salt'] = Random::alnum();
            $params['origin_password'] =  empty($params['password']) ? "123456" : $params['password'];
            $params['password'] = empty($params['password']) ?  $this->getEncryptPassword('123456', $params['salt']) : $this->getEncryptPassword($params['password'], $params['salt']);
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
            //更新班级信息
            $schoolClassModel = new Schoolclass();
            $school_id = $params['school_id'];
            $grade_id = $params['grade_id'];
            $class_id = $params['class_id'];
            //查看学校班级表是否有数据
            $has = $schoolClassModel->where("school_id",$school_id)->where("grade_id",$grade_id)->where("class_id",$class_id)->find();
            if (!$has && $school_id && $grade_id && $class_id){
                //并且年级和班级需要匹配
                $exist = (new GradeClass())->find($class_id);
                if ($exist && $exist->grade_id == $grade_id){
                    $schoolClassModel->save([
                        "school_id" => $school_id,
                        "grade_id" => $grade_id,
                        "class_id" => $class_id,
                    ]);
                }
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
//            if ($this->modelValidate) {
//                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
//                $row->validateFailException()->validate($validate);
//            }
            $params['salt'] = Random::alnum();
            $params['origin_password'] = $params['password'];
            $params['password'] = empty($params['password']) ?  $this->getEncryptPassword('123456', $params['salt']) :
                $this->getEncryptPassword($params['password'], $params['salt']);

            $result = $row->allowField(true)->save($params);
            Db::commit();
            //更新班级信息
            $schoolClassModel = new Schoolclass();
            $school_id = $params['school_id'];
            $grade_id = $params['grade_id'];
            $class_id = $params['class_id'];
            //查看学校班级表是否有数据
            $has = $schoolClassModel->where("school_id",$school_id)->where("grade_id",$grade_id)->where("class_id",$class_id)->find();
            if (!$has && $school_id && $grade_id && $class_id){
                //并且年级和班级需要匹配
                $exist = (new GradeClass())->find($class_id);
                if ($exist && $exist->grade_id == $grade_id){
                    $schoolClassModel->save([
                        "school_id" => $school_id,
                        "grade_id" => $grade_id,
                        "class_id" => $class_id,
                    ]);
                }
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");

        $id_arr = explode(",",$ids);
        foreach ($id_arr as $id){
            (new \app\admin\model\User())->where("id",$id)->delete();
        }

        $this->success();
    }


    public function vip($ids=null){
        if ($this->request->isPost()) {
            $this->token();
        }
        $this->modelValidate = true;

        if (false === $this->request->isPost()) {
            $this->view->assign('ids', $ids);
            return $this->view->fetch();
        }
        $ids = $this->request->post('ids');
        $vip_type = $this->request->post('vip_type');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!$vip_type){
            $this->error(__('No rows were updated'));
        }
        $result = false;
        Db::startTrans();
        try {
            $vipInfo = (new VipConfig())->where("id",$vip_type)->find();
            if (!$vipInfo){
                $this->error(__('No rows were updated'));
            }
            //转数组
            $idarr = explode(",",$ids);
            foreach ($idarr as $id){
                if (!$id) continue;
                $row = $this->model->get($id);
                if (!$row){
                    $this->error(__($id.'不存在'));
                }
                //如果是vip则直接跳过
                if ($row->vip_end_time > time() ){
                    continue;
                }

                //读取学校名称
                $school_name = (new School())->where("id",$row->school_id)->value("name");
                //读取年级名称
                $grade_name = (new Grade())->where("grade",$row->grade_id)->value("gradeName");
                //读取班级名称
                $class_name = (new GradeClass())->where("id",$row->class_id)->value("name");
                //获取到期时间
                $data['vip_type'] = $vip_type;
                $data['status'] = "normal";
                $data['vip_end_time'] = strtotime(date("Y-m-d 23:59:59",strtotime("+ {$vipInfo->vip_year} years")));
                $result = $row->allowField(true)->save($data);
                //插入vip订单记录
                if ($result){

                    (new StundentVipLogs())->insert(
                        [
                            'user_id' => $id,
                            'username' => $row->username,
                            'nickname' => $row->nickname,
                            'school_id' => $row->school_id,
                            'school_name' => $school_name,
                            'grade_name' => $grade_name,
                            'class_name' => $class_name,
                            'operate_type' => "add",
                            'vip_type' => $vip_type,
                            'amount' => $vipInfo->amount,
                            'type_desc' => $vipInfo->type_desc,
                            'operate_id' => $this->auth->id,
                            'vip_start_time' => time(),
                            'vip_end_time' => $data['vip_end_time'],
                            'create_time' => time(),
                        ]
                    );


                }
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage().$e->getLine());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



    public function vip_cancel($ids){

        if ($this->request->isPost()) {
            $row = $this->model->get($ids);
            $data['vip_type'] = 0;
            $data['vip_end_time'] =  null;
            $result = $row->allowField(true)->save($data);
            //读取学校名称
            $school_name = (new School())->where("id",$row->school_id)->value("name");
            //读取年级名称
            $grade_name = (new Grade())->where("grade",$row->grade_id)->value("gradeName");
            //读取班级名称
            $class_name = (new GradeClass())->where("id",$row->class_id)->value("name");
            if ($result){
                $vipInfo = (new VipConfig())->where("id", $row->vip_type)->find();
                (new StundentVipLogs())->insert(
                    [
                        'user_id' => $ids,
                        'username' => $row->username,
                        'nickname' => $row->nickname,
                        'school_id' => $row->school_id,
                        'school_name' => $school_name,
                        'grade_name' => $grade_name,
                        'class_name' => $class_name,
                        'operate_type' => "cancel",
                        'vip_type' => $row->vip_type,
                        'amount' => 0,
                        'type_desc' => "",
                        'operate_id' => $this->auth->id,
                        'create_time' => time(),
                    ]
                );
            }
            $this->success("操作成功");
        }


    }
    public function vip_try_cancel($ids){

        if ($this->request->isPost()) {
            $row = $this->model->get($ids);
            $data['vip_type'] = 0;
            $data['vip_end_time'] =  null;
            $result = $row->allowField(true)->save($data);
            $this->success("操作成功");
        }


    }

    //会员试用
    public function vip_try($ids=null){
        if ($this->request->isPost()) {
            $this->token();
        }
        $this->modelValidate = true;

        if (false === $this->request->isPost()) {
            $this->view->assign('ids', $ids);
            return $this->view->fetch();
        }
        $ids = $this->request->post('ids');
        $month = $this->request->post('month');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!$month){
            $this->error(__('试用月份不能为空'));
        }
        $result = false;
        Db::startTrans();
        try {

            //转数组
            $idarr = explode(",",$ids);
            foreach ($idarr as $id){
                if (!$id) continue;
                $row = $this->model->get($id);
                if (!$row){
                    $this->error(__($id.'不存在'));
                }
                //如果是vip则直接跳过
                if ($row->vip_type && $row->vip_end_time > time()){
                    continue;
                }

                $data['status'] = "normal";
                $data['vip_type'] = 0;
                $data['vip_end_time'] = strtotime(date("Y-m-d 23:59:59",strtotime("+ {$month} months")));;
                $result = $row->allowField(true)->save($data);
                //插入vip订单记录
                if ($result){

                    (new StundentTryLogs())->insert(
                        [
                            'user_id' => $id,
                            'nickname' => $row->nickname,
                            'try_month' => $month,
                            'operate_id' => $this->auth->id,
                            'vip_start_time' => time(),
                            'vip_end_time' => $data['vip_end_time'],
                            'create_time' => time(),
                        ]
                    );


                }
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage().$e->getLine());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
